#coding:utf-8
import urllib2
import urllib
import cookielib
import datetime
import random
import Cookie
import time
import sys
import string
import re
from sedemail import send_mail


#载入已加的linkedin用户id
idList = []
for ul in file('/home/tangjl/linkedin/addfriend/id_already_add.txt', 'r'):
    idList.extend(ul.strip().split(' '))
print len(idList)

#set proxy
# 用来保持会话
c = cookielib.LWPCookieJar()
cookie = urllib2.HTTPCookieProcessor(c)
opener = urllib2.build_opener(cookie)

# operate method
def geturlopen(hosturl, postdata = {}, headers = {}):
	# encode postdata
	enpostdata = urllib.urlencode(postdata)
	# request url
	urlrequest = urllib2.Request(hosturl, enpostdata, headers)
	# open url
	urlresponse = opener.open(urlrequest, timeout=35)
	#print c
	return urlresponse

#filenameList = ['lvyouruihead','1663752670','947281221','chens','chenshu0201','jian_lin_tang_126','jian_lin_tang_163','61869401','2037798351','364079164','jijiwaiwai911','jijiwaiwai912','jijiwaiwai913','aytx_hr','julia_alipay','Flora_guomei','letitia_ali']
filenameList = ['1663752670', '2037798351', '364079164', '61869401', '947281221', 'aytx_hr_163', 'aytx_hr', 'chens', 'chenshu0201', 'Flora_guomei', 'gaosuchu', 'jian_lin_tang_126', 'jian_lin_tang_163', 'jijiwaiwai911', 'jijiwaiwai912', 'jijiwaiwai913', 'julia_alipay', 'letitia_ali', 'lvyouglzhi', 'lvyouruihead', 'tianm_hr', 'zhangh', 'zhangj']

for filename in filenameList:
	print filename
	#读取账号登陆后的cookie
	filename_c = "/home/tangjl/linkedin/cookie/%s_c.txt"%filename
	cookies = file(filename_c, "r").read()
	mm = re.search(r'JSESSIONID="(ajax:\d+)";', cookies)
	if mm == None:
		continue
	ajax = mm.group(1)

	header = {
	"User-Agent":"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0",
	"Accept-Language":"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
	#"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
	"Accept":"text/html;q=0.9,*/*;q=0.8",
	"Cookie":cookies
	}

	#下载可能认识的人页面，并提取id与authTokens
	#url_pymk = "http://www.linkedin.com/people/pymk/hub?trk=nav_utilities_pymk_subheader"
	#req = geturlopen(url_pymk, {}, header)
	#page = req.read()
	filename_html = "/home/share/linkedin/ke可/%s_c.htm"%filename
	page = file(filename_html, "r").read()

	#正则匹配出key和authToken并去重
	pattern = re.compile(r'view\?id=(\d+)\&amp;authType=name\&amp;authToken=(\w+)\&amp')
	matchList = pattern.findall(page)
	if len(matchList) == 0:
		pattern = re.compile(r'profile/view\?id=(\d+)\&authType=name\&authToken=(\w+)"')
		matchList = pattern.findall(page)
	matchList = list(set(matchList))
	print "这个可能认识的人页面共有%d个人"%len(matchList)
	for idd in matchList:
		try:
			print idd[0],idd[1]
			key = idd[0]
			authToken = idd[1]
			if key in idList:
				print "该用户已经被邀请过了！！！"
				continue

			postdata = {
			"memIds":key,
			"authTokens":authToken,
			"authTypes":"name",
			#"connectionParam":"member_desktop_pymk_landing-connect-hub",
			"csrfToken":ajax,
			#"trk":"connect_hub_pymk_edit_invite",
			#"isAjax":"true"
			}
			#在可能认识的人中建立联系
			ireca_url = "http://www.linkedin.com/people/contacts-pymk-invite-submit"
			req = geturlopen(ireca_url, postdata, header)
			response_page = req.read()
			if 25<=len(response_page)/1000<=28:
				if filename == "chens" or filename == "lvyouruihead" :
					send_mail("chens@glzhi.com","抓取linkedin简历", "小澍，Excuse me，账号："+filename+" Cookie has expired, please update！！！")
				file("3.html", "w").write(response_page)
				send_mail("tangjl@glzhi.com","抓取linkedin简历", "账号："+filename+"的cookie已失效，请及时更新！！！")
				break
			file("3.html", "w").write(response_page)

			#将发送过邀请的key加到idList中，并将key与authToken写到文件中
			idList.append(key)
			file("/home/tangjl/linkedin/addfriend/id_already_add.txt", "a").write(key+'\n')
			file("/home/tangjl/linkedin/addfriend/info_already_add.txt", "a").write(key+',,'+authToken+'\n')
			print "===>已发送邀请：%d个，发送这次邀请的是：%s！！！"%(len(idList), filename)
			time.sleep(3)
		except:
			pass
